import 'package:date_format/date_format.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:largefriends/res/lf_color.dart';
import 'package:largefriends/res/lf_text_style.dart';
import 'package:largefriends/utils/lf_keyboard.dart';

import '../res/lf_fonts.dart';
import '../res/lf_int_ext.dart';

class BirthdayInputWidget extends StatefulWidget {
  final Function(String inputValue) onValue;
  final DateTime? initTime;
  const BirthdayInputWidget({Key? key, required this.onValue, this.initTime})
      : super(key: key);

  @override
  _BirthdayInputWidgetState createState() {
    return _BirthdayInputWidgetState();
  }
}

class _BirthdayInputWidgetState extends State<BirthdayInputWidget> {
  RxString inputValue = "".obs;
  RxString hintValue = "MM/DD/YYYY".obs;
  TextEditingController controller = TextEditingController();
  FocusNode focusNode = FocusNode();

  @override
  void initState() {
    super.initState();
    if (widget.initTime != null) {
      inputValue.value = formatDate(widget.initTime!, [mm, '/', dd, '/', yyyy]);
      hintValue.value = "";
    }
    focusNode.addListener(() {
      if (focusNode.hasFocus) {
        // 监听软键盘事件
        RawKeyboard.instance.addListener(_handleKey);
      } else {
        // 取消监听软键盘事件
        RawKeyboard.instance.removeListener(_handleKey);
      }
    });
  }

  @override
  void dispose() {
    focusNode.dispose();
    controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        InkWell(
          child: Obx(() => Text(
                inputValue.value,
                style: lfTextStyle(sp: 18.sp, fontFamily: fontMedium),
              )),
          onTap: () {
            showSoftKeyboard(focusNode);
          },
        ),
        Expanded(
          child: GestureDetector(
            onLongPress: () {},
            child: Obx(() {
              return TextField(
                decoration: InputDecoration(
                    isCollapsed: true,
                    fillColor: Colors.white,
                    //去掉莫名其妙的padding
                    hintText: hintValue.value,
                    hintStyle: lfTextStyle(
                        sp: 18.sp,
                        fontFamily: fontMedium,
                        color: color210215.withAlpha(128)),
                    contentPadding: EdgeInsets.symmetric(vertical: 8.h),
                    enabledBorder: InputBorder.none,
                    focusedBorder: InputBorder.none,
                    disabledBorder: InputBorder.none,
                    focusedErrorBorder: InputBorder.none,
                    border: InputBorder.none),
                onChanged: (value) {
                  _onTextChange(value);
                },
                keyboardType: TextInputType.number,
                enableInteractiveSelection: false,
                maxLines: 1,
                minLines: 1,
                controller: controller,
                focusNode: focusNode,
              );
            }),
          ),
        )
      ],
    );
  }

  int duration = 0;
  void _handleKey(RawKeyEvent event) {
    if (event.runtimeType == RawKeyDownEvent && (event is RawKeyDownEvent)) {
      if (event.logicalKey == LogicalKeyboardKey.backspace) {
        var current = DateTime.now().millisecondsSinceEpoch;
        if (current - duration > 100) {
          _deleteValueAction();
          duration = current;
        }
      }
    }
  }

  _deleteValueAction() {
    controller.text = "";
    if (inputValue.value.isEmpty) {
      inputValue.value = '';
      hintValue.value = "MM/DD/YYYY";
    } else if (inputValue.value.length == 1) {
      inputValue.value = '';
      hintValue.value = "MM/DD/YYYY";
    } else if (inputValue.value.length == 3) {
      inputValue.value = inputValue.value.substring(0, 1);
      hintValue.value = "M/DD/YYYY";
    } else if (inputValue.value.length == 4) {
      inputValue.value = inputValue.value.substring(0, 3);
      hintValue.value = "DD/YYYY";
    } else if (inputValue.value.length == 6) {
      inputValue.value = inputValue.value.substring(0, 4);
      hintValue.value = "D/YYYY";
    } else if (inputValue.value.length == 7) {
      inputValue.value = inputValue.value.substring(0, 6);
      hintValue.value = "YYYY";
    } else if (inputValue.value.length == 8) {
      inputValue.value = inputValue.value.substring(0, 7);
      hintValue.value = "YYY";
    } else if (inputValue.value.length == 9) {
      inputValue.value = inputValue.value.substring(0, 8);
      hintValue.value = "YY";
    } else if (inputValue.value.length == 10) {
      inputValue.value = inputValue.value.substring(0, 9);
      hintValue.value = "Y";
    }
    widget.onValue.call(inputValue.value);
  }

  _onTextChange(String value) {
    var num = parseInt(value);
    controller.text = "";
    if (inputValue.value.isEmpty) {
      if (num < 2) {
        inputValue.value = '$num';
        hintValue.value = "M/DD/YYYY";
      }
    } else if (inputValue.value.length == 1) {
      var month = parseInt(inputValue.value) * 10 + num;
      if (month > 0 && month < 13) {
        //月份肯定是1~12
        inputValue.value = '${inputValue.value}$num/';
        hintValue.value = "DD/YYYY";
      }
    } else if (inputValue.value.length == 3) {
      if (num < 4) {
        inputValue.value = '${inputValue.value}$num';
        hintValue.value = "D/YYYY";
      }
    } else if (inputValue.value.length == 4) {
      var day =
          parseInt(inputValue.value.substring(3, 4)) * 10 + num; //日期肯定是1~31
      if (day > 0 && day < 32) {
        inputValue.value = '${inputValue.value}$num/';
        hintValue.value = "YYYY";
      }
    } else if (inputValue.value.length == 6) {
      if (num == 1 || num == 2) {
        inputValue.value = '${inputValue.value}$num';
        hintValue.value = "YYY";
      }
    } else if (inputValue.value.length == 7) {
      var yearStar = parseInt(inputValue.value.substring(6, 7)) * 10 + num;
      if (yearStar > 18 && yearStar < 21) {
        //年份前两位数肯定是19,或者20
        inputValue.value = '${inputValue.value}$num';
        hintValue.value = "YY";
      }
    } else if (inputValue.value.length == 8) {
      var yearStar = parseInt(inputValue.value.substring(6, 8)) * 10 + num;
      var currentYear = DateTime.now().year;
      if ((yearStar > (currentYear - 99) / 10) &&
          yearStar < (currentYear - 19) / 10) {
        //确保第三位数字在合理范围内, 最小18岁,最大99岁
        inputValue.value = '${inputValue.value}$num';
        hintValue.value = "Y";
      }
    } else if (inputValue.value.length == 9) {
      var yearStar = parseInt(inputValue.value.substring(6, 9)) * 10 + num;
      var currentYear = DateTime.now().year;
      if ((yearStar > currentYear - 99) && yearStar < (currentYear - 19)) {
        //确保第三位数字在合理范围内, 最小18岁,最大99岁
        inputValue.value = '${inputValue.value}$num';
        hintValue.value = "";
      }
    }
    widget.onValue.call(inputValue.value);
  }
}
